package com.zzy.msm.controller;

import com.zzy.commonutils.R;
import com.zzy.msm.service.MsmService;
import com.zzy.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author KAZU
 * @Date 2023/1/19 10:39
 * @Version 1.0
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class Msmontroller {

	@Autowired
	private MsmService msmService;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	/**
	 * 发送短信方法
	 * */
	@GetMapping("send/{phone}")
	public R sendMsm(@PathVariable String phone) throws Exception {
		// 1 从redis获取验证码，如果取到直接返回
		String code = redisTemplate.opsForValue().get("phone");
		if (!StringUtils.isEmpty(code)) {
			return R.ok();
		}
		// 2 如果取不到，进行阿里云发送
		// 生成随机数，发给阿里云
		code = RandomUtil.getFourBitRandom();
		Map<String, Object> param = new HashMap<>();
		param.put("code", code);
		// 调用service发送短信的方法
		Boolean isSend = msmService.send(param, phone);
//		Boolean isSend = msmService.send(code, phone);
		if (isSend) {
			// 发送成功，把发送成功的验证码放到redis中，设置有效时间
			redisTemplate.opsForValue().set("phone"+phone, code, 5, TimeUnit.MINUTES);
			return R.ok();
		} else {
			return R.error().message("短信发送失败");
		}
	}

}

